﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace Aribaccio
{
    /// <summary>
    /// 定义Xml序列反序列类
    /// </summary>
    public static class ExtendXmlSerialize
    {
        /// <summary>
        /// 实体类转换成XML[XML序列化]
        /// </summary>
        /// <typeparam name="T">实体类模型</typeparam>
        /// <param name="obj">实体类模型对象</param>
        /// <returns>XML格式字符串</returns>
        public static string XmlSerialize<T>(this T obj) where T : class, new()
        {
            try
            {
                if (obj == null) return string.Empty;
                //将实体类转换成XML需要使用XmlSerializer类的Serialize方法，将实体类序列化
                using (StringWriter sw = new StringWriter())
                {
                    Type t = obj.GetType();
                    XmlSerializer serializer = new XmlSerializer(obj.GetType());
                    serializer.Serialize(sw, obj);
                    sw.Close();
                    return sw.ToString();
                }
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// 将XML转换成实体类[XML反序列]
        /// </summary>
        /// <typeparam name="T">实体类模型</typeparam>
        /// <param name="strXML">XML格式字符串</param>
        /// <returns>实体类模型对象</returns>
        public static T? XmlDeserialize<T>(this string strXML) where T : class, new()
        {
            try
            {
                //把XML转换成相应的实体类，需要使用到XmlSerializer类的Deserialize方法，将XML进行反序列化。
                using (StringReader sr = new StringReader(strXML))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    return serializer.Deserialize(sr) as T;
                }
            }
            catch (Exception)
            {
                return default(T);
            }
        }
    }
}
